//
//  KICropView.m
//  搞起
//
//  Created by Alex on 14-12-9.
//  Copyright (c) 2014年 Alex. All rights reserved.
//

#import "KICropView.h"
#import "XXTool.h"

@implementation KICropView
{
    UIButton* confirm;
    UIButton* cancel;
}


-(id)initWithFrame:(CGRect)frame
          WithSize:(CGSize)size
{
    self=[super initWithFrame:frame];
    if(self)
    {
        //-----------------------------------------------------------------------------------
        //图片选择框
        rectSize=size;
        _imageView=[[KICropImageView alloc] initWithFrame:frame];
        [_imageView setCropSize:rectSize];
        [self addSubview:_imageView];
        
        //-----------------------------------------------------------------------------------
        //确认，取消
        confirm=[UIButton buttonWithType:UIButtonTypeSystem];
        
        [confirm setBackgroundColor:[XXTool colorWithProject]];
        [confirm setTintColor:[UIColor whiteColor]];
        [confirm setImage:[UIImage imageNamed:@"yes.png"] forState:UIControlStateNormal];
        [confirm addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:confirm];
        
        cancel=[UIButton buttonWithType:UIButtonTypeSystem];
        [cancel.layer setCornerRadius:confirm.frame.size.height/2];
        [cancel setBackgroundColor:[XXTool colorWithProject]];
        [cancel setTintColor:[UIColor whiteColor]];
        [cancel setImage:[UIImage imageNamed:@"no.png"] forState:UIControlStateNormal];
        [cancel addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cancel];
    }
    return self;
}

-(void)setImage:(UIImage*)image
{
    image=[KICropView fixOrientation:image];
    [_imageView setImage:image];
}

-(void)back
{
    [UIView animateWithDuration:0.3 animations:^(void)
     {
         self.center=CGPointMake(self.center.x, self.center.y*3);
     }completion:^(BOOL finished)
     {
         [self removeFromSuperview];
         if([_delegate respondsToSelector:@selector(cropViewDidClickCancel:)])
         {
             [_delegate cropViewDidClickCancel:self];
         }
     }];
}

-(void)save
{
    if([_delegate respondsToSelector:@selector(cropView:didClickSaveImage:ImageRect:)])
    {
        [_delegate cropView:self
          didClickSaveImage:[_imageView cropImage]
                  ImageRect:[_imageView convertRect:CGRectMake((_imageView.frame.size.width-rectSize.width)/2,
                                                               (_imageView.frame.size.height-rectSize.height)/2,
                                                               rectSize.width,
                                                               rectSize.height)
                                             toView:self]];
        [UIView animateWithDuration:0.2 animations:^(void)
         {
             self.alpha=0;
         }completion:^(BOOL finished)
         {
             [self removeFromSuperview];
             //self.hidden=YES;
             //self.alpha=1;
         }];
    }
}




+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    _imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    //[_imageView setCropSize:rectSize];
    confirm.frame=CGRectMake(self.frame.size.width-100, self.frame.origin.y+64+60, 30, 30);
    [confirm.layer setCornerRadius:confirm.frame.size.height/2];
    cancel.frame=CGRectMake(self.frame.size.width-50, self.frame.origin.y+64+60, 30, 30);
    [cancel.layer setCornerRadius:cancel.frame.size.height/2];
    
}

@end
